package com.ruoyi.web.controller.module.product;

import java.math.BigDecimal;
import java.util.*;

import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.MathUtil;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.system.domain.module.estate.Estate;
import com.ruoyi.system.domain.module.mer.Mer;
import com.ruoyi.system.domain.module.product.*;
import com.ruoyi.system.domain.module.property.Property;
import com.ruoyi.system.service.module.estate.IEstateService;
import com.ruoyi.system.service.module.mer.IMerService;
import com.ruoyi.system.service.module.product.*;
import com.ruoyi.system.service.module.property.IPropertyService;
import com.ruoyi.web.controller.common.BaseController;
import com.vdurmont.emoji.EmojiParser;
import lombok.RequiredArgsConstructor;
import javax.validation.constraints.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 订单详情内容  订单里面的 商品列Controller
 *
 * @author ruoyi
 * @date 2021-09-25
 */
@Validated
@Api(value = "订单详情内容  订单里面的 商品列控制器", tags = {"订单详情内容  订单里面的 商品列管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/module/order/info")
public class ProductOrderInfoController extends BaseController {

    private final IProductOrderService productOrderService;
    private final IProductOrderInfoService productOrderInfoService;
    private final IProductAttrValueService productAttrValueService;
	private final IPropertyService propertyService;
	private final IEstateService estateService;
	private final IMerService merService;
	private final IProductService productService;
	private final IProductTypeService productTypeService;


    /**
     * 查询订单详情内容  订单里面的 商品列列表
     */
    @ApiOperation("查询订单详情内容  订单里面的 商品列列表")
    @PreAuthorize("@ss.hasPermi('module:orderinfo:list')")
    @GetMapping("/list")
    public TableDataInfo<ProductOrderInfo> list(@Validated ProductOrderInfo productOrderInfo) {
        QueryWrapper<ProductOrderInfo> qw = new QueryWrapper<>();
        if(productOrderInfo.getOrderId() != null){
            qw.eq("order_id",productOrderInfo.getOrderId());
        }

        TableDataInfo<ProductOrderInfo> td = PageUtils.buildDataInfo(productOrderInfoService.page(PageUtils.buildPage(),qw));
        List<ProductOrderInfo> list = td.getRows();
        list.forEach(orderInfo -> {
			if(StrUtil.isEmpty(orderInfo.getSkuName())){
				ProductAttrValue productAttrValue = productAttrValueService.findById(orderInfo.getSkuId());
				if(productAttrValue!=null){
					orderInfo.setSkuName(productAttrValue.getSku());
				}
			}
            Product product = productService.findById(orderInfo.getProductId());
            if(product!=null){
				orderInfo.setProductName(product.getStoreName());
			}
        });
        ProductOrder order = productOrderService.findById(productOrderInfo.getOrderId());
        if(order!=null){
			Mer mer = merService.getById(order.getMerId());
			if(mer != null){
				order.setShopName(mer.getShopName());
			}

			Estate estate = estateService.findById(order.getEstateId());
			if(estate!=null){
				order.setEstateName(estate.getEstateName());
			}

			if(StrUtil.isNotEmpty(order.getRealName())){
				order.setRealName(EmojiParser.parseToUnicode(order.getRealName()));
			}

			Property property = propertyService.findById(order.getPropertyId());
			if(property!=null){
				order.setPropertyName(property.getPropertyName());
			}
		}
        Map<String,Object> map = new HashMap<>();
        map.put("order",order);

        td.setOtherData(map);
        return td;
    }

    /**
     * 导出订单详情内容  订单里面的 商品列列表
     */
    @ApiOperation("导出订单详情内容  订单里面的 商品列列表")
    @PreAuthorize("@ss.hasPermi('module:orderinfo:export')")
    @Log(title = "订单详情内容  订单里面的 商品列", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult<ProductOrderInfo> export(@Validated ProductOrderInfo productOrderInfo) {
        List<ProductOrderInfo> list = productOrderInfoService.list();
        ExcelUtil<ProductOrderInfo> util = new ExcelUtil<ProductOrderInfo>(ProductOrderInfo.class);
        return util.exportExcel(list, "订单详情内容  订单里面的 商品列");
    }

    /**
     * 获取订单详情内容  订单里面的 商品列详细信息
     */
    @ApiOperation("获取订单详情内容  订单里面的 商品列详细信息")
    @PreAuthorize("@ss.hasPermi('module:orderinfo:query')")
    @GetMapping("/{id}")
    public AjaxResult<ProductOrderInfo> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {
        ProductOrderInfo productOrderInfo = productOrderInfoService.getById(id);
        if(productOrderInfo!=null){

		}
        return AjaxResult.success(productOrderInfo);
    }

    /**
     * 新增订单详情内容  订单里面的 商品列
     */
    @ApiOperation("新增订单详情内容  订单里面的 商品列")
    @PreAuthorize("@ss.hasPermi('module:orderinfo:add')")
    @Log(title = "订单详情内容  订单里面的 商品列", businessType = BusinessType.INSERT)
    @RepeatSubmit
    @PostMapping()
    public AjaxResult<Void> add(@Validated(AddGroup.class) @RequestBody ProductOrderInfo productOrderInfo) {

		SysUser sysUser = getUser();
		productOrderInfo.setIsDel(0);
		productOrderInfo.setOpSysUserId(sysUser.getUserId());
		productOrderInfo.setOpSysUserName(sysUser.getNickName());
		Product product = productService.getById(productOrderInfo.getProductId());
		ProductType type = productTypeService.getById(product.getCateId());
		productOrderInfo.setProductName(product.getStoreName());
		if(productOrderInfo.getCount()!= null && productOrderInfo.getSinglePrice()!= null){
			double totalMoney = productOrderInfo.getCount() * productOrderInfo.getSinglePrice().doubleValue();
			productOrderInfo.setTotalMoney(BigDecimal.valueOf(MathUtil.getDoubleUp(totalMoney)));
		}
		boolean bl = productOrderInfoService.save(productOrderInfo);
		if(bl){
			int ret = productOrderInfoService.resetOrderTotalMoney(productOrderInfo);
			if (ret > 0){
				QueryWrapper<ProductOrderInfo> qw = new QueryWrapper<>();
				qw.eq("product_id",productOrderInfo.getProductId());
				qw.eq("order_id",productOrderInfo.getOrderId());
				TableDataInfo<ProductOrderInfo> td = PageUtils.buildDataInfo(productOrderInfoService.page(PageUtils.buildPage(),qw));
				List<ProductOrderInfo> orderInfos = td.getRows();
				for (ProductOrderInfo orderInfo:orderInfos){
					orderInfo.setSkuName("默认");
					Product product1 = productService.getById(orderInfo.getProductId());
					orderInfo.setProductName(product1.getStoreName());
				}
			}
			return toAjax(ret > 0 ? 1 : 0);
		}
        return toAjax(bl ? 1 : 0);
    }

    /**
     * 修改订单详情内容  订单里面的 商品列
     */
    @ApiOperation("修改订单详情内容  订单里面的 商品列")
    @PreAuthorize("@ss.hasPermi('module:orderinfo:edit')")
    @Log(title = "订单详情内容  订单里面的 商品列", businessType = BusinessType.UPDATE)
    @RepeatSubmit
    @PutMapping()
    public AjaxResult<Void> edit(@Validated(EditGroup.class) @RequestBody ProductOrderInfo productOrderInfo) {
		SysUser sysUser = getUser();
		productOrderInfo.setOpSysUserId(sysUser.getUserId());
		productOrderInfo.setOpSysUserName(sysUser.getNickName());
		if (productOrderInfo.getSinglePrice()!=null){
			productOrderInfo.setTotalMoney(BigDecimal.valueOf(productOrderInfo.getSinglePrice().doubleValue() * productOrderInfo.getCount()));
		}
		if (productOrderInfo.getCount()!=null){
			ProductOrderInfo productOrderInfos = productOrderInfoService.selectByUniqueColumn("id",productOrderInfo.getId());
			productOrderInfo.setTotalMoney(BigDecimal.valueOf(productOrderInfos.getSinglePrice().doubleValue() * productOrderInfo.getCount()));
			productOrderInfo.setOrderId(productOrderInfos.getOrderId());
		}
        boolean bl = productOrderInfoService.updateById(productOrderInfo);
        if(bl){
            int ret = productOrderInfoService.resetOrderTotalMoney(productOrderInfo);
            return toAjax(ret > 0 ? 1 : 0);
        }
        return toAjax(bl ? 1 : 0);
    }

    /**
     * 删除订单详情内容  订单里面的 商品列
     */
    @ApiOperation("删除订单详情内容  订单里面的 商品列")
    @PreAuthorize("@ss.hasPermi('module:orderinfo:remove')")
    @Log(title = "订单详情内容  订单里面的 商品列" , businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult<Void> remove(@NotEmpty(message = "主键不能为空")  @PathVariable Long[] ids) {

		SysUser sysUser = getUser();

		for (Long id : ids){
			ProductOrderInfo orderInfo = productOrderInfoService.findById(id);
			if(orderInfo!= null){
				orderInfo.setIsDel(1);
				orderInfo.setDelSysUserId(sysUser.getUserId());
				orderInfo.setDelSysUserName(sysUser.getNickName());
				orderInfo.setDelTime(new Date());
				boolean bl = productOrderInfoService.updateById(orderInfo);
				if(bl){
					int ret = productOrderInfoService.resetOrderTotalMoney(orderInfo);
					if(ret > 0){
						return toAjax(bl ? 1 : 0);
					}
				}
			}
		}
        return toAjax(0);
    }

}
